import time
import pymysql
import requests
from lxml import etree

class DB:
    def __init__(self,host='',port=3306,user='',password='',db='',charset='utf8'):
        self.conn=pymysql.connect(host=host,port=port,user=user,password=password,database=db,charset=charset)
        self.cur =self.conn.cursor()

    def __enter__(self):
        return self.cur
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.conn.commit()
        self.cur.close()
        self.conn.close()

def getdata(url):
    # url='https://www.mmonly.cc/ktmh/mhrw/list_31_1.html'
    head={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'}
    responce=requests.get(url,headers=head)  #拼接头
    responce.encoding="gb2312"#转码
    html=etree.HTML(responce.text)#自动补全
    return html
def getData(html,db):
    div=html.xpath('//div[@class="ABox"]')
    # print(div)
    for a in div:
        href=a.xpath('./a/@href')   #总链接
        img=a.xpath('./a/img/@src')  # 图片地址
        alt=a.xpath('./a/img/@alt')   #图片名
        # print(href,img,alt)
        all=[href,img,alt]
        db.execute('insert into mmonly(href,src,name_)values(%s,%s,%s)',all)
def main(db):
    for i in range(1,6):  #循环的范围
        url="https://www.mmonly.cc/ktmh/mhrw/list_31_"+str(i)+".html"   #循环网址
        html=getdata(url)      #
        getData(html,db)
        time.sleep(1)
if __name__ == '__main__':
    with DB(host='localhost',user='usert',password='123456',db='guojiuchang') as db:
        main(db)